package com.rtf.framework.web.http;

import com.rtf.framework.common.config.AppProperties;
import com.rtf.framework.common.util.UtilString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@RequestMapping("${server.error.path:${error.path:/error}}")
public class AppErrorController extends AbstractErrorController {

    @Autowired
    private ServerProperties serverProperties ;

    @Autowired
    private AppProperties appProperties ;

    public AppErrorController(ErrorAttributes errorAttributes, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorViewResolvers);
    }

    protected ErrorProperties getErrorProperties() {
        return this.serverProperties.getError() ;
    }

    @Override
    public String getErrorPath() {
        return this.getErrorProperties().getPath();
    }

    @RequestMapping(produces = "text/html")
    public String errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        log.error("{} 处理错误，转到: {}" , request.getRequestURI() , appProperties.getErrorPath() ) ;
        return "redirect:" + appProperties.getErrorPath()  ;
    }

//    @RequestMapping
//    @ResponseBody
//    public ResponseParam error(HttpServletRequest request) {
//        if( ! UtilString.equalsIgnoreCase( request.getRequestURI() , "/error" ) ){
//            log.error("{} 处理错误，返回错误信息" , request.getRequestURI() ) ;
//        }
//
//        return ResponseParam.fail().message("服务端处理失败，请联系管理员。") ;
//    }

    @RequestMapping
    @ResponseBody
    public String error(HttpServletRequest request) {
        if( ! UtilString.equalsIgnoreCase( request.getRequestURI() , "/error" ) ){
            log.error("{} 处理错误，返回错误信息" , request.getRequestURI() ) ;
        }

        return "";
    }

}
